package org.jeecg.modules.basic.guest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.basic.entry.util.HttpRequestToPrivate;
import org.jeecg.modules.basic.entry.util.ImageUtil;
import org.jeecg.modules.basic.entry.util.SenseTimeEnumToPrivate;
import org.jeecg.modules.basic.entry.util.SenseTimeEnumToPublic;
import org.jeecg.modules.basic.guest.entity.LwgyInoutGuest;
import org.jeecg.modules.basic.guest.mapper.LwgyInoutGuestMapper;
import org.jeecg.modules.basic.guest.service.ILwgyInoutGuestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.jeecg.modules.basic.entry.util.HttpRequestToPrivate.sendGet;
import static org.jeecg.modules.basic.entry.util.HttpRequestToPrivate.sendPost;
import static org.jeecg.modules.basic.entry.util.StringUtil.getBytes;
import static org.jeecg.modules.basic.entry.util.StringUtil.getMD5;

/**
 * @Description: 外来人员管理
 * @Author: jeecg-boot
 * @Date:   2021-03-17
 * @Version: V1.0
 */
@Service
public class LwgyInoutGuestServiceImpl extends ServiceImpl<LwgyInoutGuestMapper, LwgyInoutGuest> implements ILwgyInoutGuestService {

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @Autowired
    private LwgyInoutGuestMapper lwgyInoutGuestMapper;

//公有云接口
    @Override
    public String saveGuestToPublic(LwgyInoutGuest lwgyInoutGuest) throws Exception {

        //本机要上传的图片位置
       // private final static String path = "F://123.png";
        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.GUEST_URL.getMsg();        //表单文本参数
        Map<String, Object> params = new HashMap();
        //表单文件参数
        Map<String, byte[]> fileParams = new HashMap();

        String path=upLoadPath+ File.separator+ lwgyInoutGuest.getGuestPhoto();
        if (path.contains("//")) {
            path = path.replace("//", "/");
        }
        if (path.contains("\'")) {
            path = path.replace("\'", "/");
        }
        String timestamp = String.valueOf(System.currentTimeMillis());

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String fromDateString = formatter.format(lwgyInoutGuest.getGuestTime());
        String toDateString = formatter.format(lwgyInoutGuest.getToTime());


        //添加表单文本参数
        {
            params.put("name", lwgyInoutGuest.getGuestName());//人员姓名
            params.put("mobile",lwgyInoutGuest.getGuestMobile() );//手机号
            params.put("remark",lwgyInoutGuest.getGuestRemark());//备注
            params.put("groups", lwgyInoutGuest.getGuestGroupid());//人员组列表
            params.put("receptionUserId",lwgyInoutGuest.getReceptionUserid() );//接待员工Id
            params.put("guestPurpose",lwgyInoutGuest.getGuestPurpose());//来访目的

            params.put("dateTimeFrom",fromDateString);//到访时间
            params.put("dateTimeTo",toDateString);//到访时间
            params.put("gender", lwgyInoutGuest.getGuestGender());//性别
            params.put("guestCompany",lwgyInoutGuest.getGuestConpany() );//客所在企业
            params.put("position",lwgyInoutGuest.getGuestPosition() );//职位
            params.put("force","1" );//强制添加

            params.put("app_key", SenseTimeEnumToPublic.APP_KEY.getMsg());
            params.put("timestamp", timestamp);
            params.put("sign", getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg()));
        }


        File avatar_file = new File(path);

        String name = avatar_file.getName();

        //添加表单文件参数
        {
            fileParams.put("avatarFile", getBytes(avatar_file));
        }
        String result = new String(sendPost(url, params, fileParams,name));
        System.out.println("========result========:"+result);
        return result;

    }
    @Override
    public String queryQrcodeByIdToPublic(String userId){
        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.QRCODE_URL.getMsg();//https://link.bi.sensetime.com/api/v1/group
        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
        String params ="user_id="+userId+"" +
                "&app_key="+ SenseTimeEnumToPublic.APP_KEY.getMsg()+"" +
                        "&timestamp="+timestamp+"" +
                        "&sign="+ getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg());
        String result = sendGet(url, params);
        return result;
    }


    @Override
    public String queryUser(int type,String name,String mobile,String idNumber) throws UnsupportedEncodingException {
        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.QUERY_USER.getMsg();//https://link.bi.sensetime.com/api/v1/group
        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
        String params ="&type="+type+"" +
                "&name="+URLEncoder.encode(name,"utf-8")+"" +
                "&mobile="+mobile+"" +
                "&idNumber="+idNumber+"" +
                "&app_key="+ SenseTimeEnumToPublic.APP_KEY.getMsg()+"" +
                "&timestamp="+timestamp+"" +
                "&sign="+ getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg());
        String result = sendGet(url,params);
        return result;
    }

    @Override
    public String updateGuest(LwgyInoutGuest lwgyInoutGuest ) throws Exception {



        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String fromDateString = formatter.format(lwgyInoutGuest.getGuestTime());
        String toDateString = formatter.format(lwgyInoutGuest.getToTime());

        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.UPDATEGUEST_URL.getMsg()+"/"+lwgyInoutGuest.getGuestId();        //表单文本参数
        Map<String, Object> params = new HashMap();
        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
        {
            params.put("id", lwgyInoutGuest.getGuestId());//人员姓名
            params.put("name", lwgyInoutGuest.getGuestName());//人员姓名
            params.put("mobile",lwgyInoutGuest.getGuestMobile() );//手机号
            params.put("remark",lwgyInoutGuest.getGuestRemark());//备注
            params.put("groups", lwgyInoutGuest.getGuestGroupid());//人员组列表
            params.put("receptionUserId",lwgyInoutGuest.getReceptionUserid() );//接待员工Id
            params.put("guestPurpose",lwgyInoutGuest.getGuestPurpose());//来访目的

            params.put("dateTimeFrom",fromDateString);//到访时间
            params.put("dateTimeTo",toDateString);//到访时间
            params.put("gender", lwgyInoutGuest.getGuestGender());//性别
            params.put("guestCompany",lwgyInoutGuest.getGuestConpany() );//客所在企业
            params.put("position",lwgyInoutGuest.getGuestPosition() );//职位
            params.put("force","1" );//强制添加


            params.put("app_key", SenseTimeEnumToPublic.APP_KEY.getMsg());
            params.put("timestamp", timestamp);
            params.put("sign", getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg()));
        }
        String result = new String(sendPost(url, params, null,null));
        System.out.println("========result========:"+result);
        return result;

    }



    /**
     * 远程开门
     *
     * */
    @Override
    public String deviceOpen() {


        String url = SenseTimeEnumToPublic.HOST.getMsg() + SenseTimeEnumToPublic.DEVICE_OPEN.getMsg();        //表单文本参数
        Map<String, Object> params = new HashMap();

        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
        {
            params.put("id", SenseTimeEnumToPublic.DEVICE_ID.getMsg());
            params.put("app_key", SenseTimeEnumToPublic.APP_KEY.getMsg());
            params.put("timestamp", timestamp);
            params.put("sign", getMD5(timestamp + "#" + SenseTimeEnumToPublic.APP_SECRET.getMsg()));
        }
        String result = null;
        try {
            result = new String(sendPost(url, params, null,null));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("========result========:"+result);
        return result;

    }

    //公有云有云接口------end
    //私有云接口------
    @Override
    public String saveGuestToPrivate(LwgyInoutGuest lwgyInoutGuest) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String fromDateString = formatter.format(lwgyInoutGuest.getGuestTime());
        String toDateString = formatter.format(lwgyInoutGuest.getToTime());
        //本机要上传的图片位置
        String url = SenseTimeEnumToPrivate.HOST.getMsg() + SenseTimeEnumToPrivate.SAVEUSER_URL.getMsg();        //表单文本参数
        JSONObject params=new JSONObject();
        params.put("type", 2);
        params.put("name", lwgyInoutGuest.getGuestName());//人员姓名
        params.put("mobile",lwgyInoutGuest.getGuestMobile() );//手机号
        params.put("remark",lwgyInoutGuest.getGuestRemark());//备注
        //params.put("groups", lwgyInoutGuest.getGuestGroupid());//人员组列表
        params.put("receptionUserId",lwgyInoutGuest.getReceptionUserid() );//接待员工Id
        params.put("guestPurpose",lwgyInoutGuest.getGuestPurpose());//来访目的
        params.put("dateTimeFrom",fromDateString);//到访时间
        params.put("dateTimeTo",toDateString);//到访时间
        params.put("gender", lwgyInoutGuest.getGuestGender());//性别
        params.put("guestCompany",lwgyInoutGuest.getGuestConpany() );//客所在企业
        params.put("position",lwgyInoutGuest.getGuestPosition() );//职位


        String result;
        if(lwgyInoutGuest.getGuestPhoto() != null && !lwgyInoutGuest.getGuestPhoto().equals("")&& !lwgyInoutGuest.getGuestPhoto().equals("undefined")){
        }            //表单文件参数
        String path=upLoadPath+ File.separator+ lwgyInoutGuest.getGuestPhoto();
        path = reformPath(path);
        params.put("avatarBytes", ImageUtil.getImageStr(path));

        result = new String(HttpRequestToPrivate.sendPostByJSON(url, params.toString()));
        System.out.println("========result========:"+result);
        return result;


    }

    @Override
    public String queryQrcodeByIdToPrivate(String userId){
        String url = SenseTimeEnumToPrivate.HOST.getMsg() + SenseTimeEnumToPrivate.QRCODE_URL.getMsg();//https://link.bi.sensetime.com/api/v1/group
        String timestamp = String.valueOf(System.currentTimeMillis());
        //添加表单文本参数
       /* String params ="user_id="+userId+"" +
                "&app_key="+ SenseTimeEnumToPrivate.APP_KEY.getMsg()+"" +
                "&timestamp="+timestamp+"" +
                "&sign="+ getMD5(timestamp + "#" + SenseTimeEnumToPrivate.APP_SECRET.getMsg());
  */      String params ="&user_id="+userId;
        String result = HttpRequestToPrivate.sendGet(url, params);
        return result;
    }

    @Override
    public void changeGuestState(){
        lwgyInoutGuestMapper.changeGuestState();
    }
    /***
     * 通过身份证号检查系统中是否存在该访客
     */

    @Override
    public boolean checkGuest(String idCard){
        int a =  lwgyInoutGuestMapper.checkGuset(idCard);
        if(a>0){
            return true;
        }else{
            return false;
        }
    }
    public String reformPath(String path){
        if (path.contains("//")) {
            path = path.replace("//", "/");
        }
        if (path.contains("\'")) {
            path = path.replace("\'", "/");
        }

        return path;
    }

    //查询访客列表

    public  List<LwgyInoutGuest> getGuest(String mobile) {
        //添加商汤系统中
        QueryWrapper<LwgyInoutGuest> queryWrapper=new QueryWrapper<>();

        queryWrapper.eq("guest_mobile",mobile);
        List<LwgyInoutGuest> list = lwgyInoutGuestMapper.selectList(queryWrapper);

         return list;
    }

}
